import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'
import qs from 'qs'
import {
  getCurDate,
  setSessionStorage,
  getSessionStorage,
  removeSessionStorage,
  setLocalStorage,
  getLocalStorage,
  removeLocalStorage
} from './common.js'

// 设置axios基础路径，通过本地代理转发到后端8080
axios.defaults.baseURL = '/api/'

// 添加请求拦截器，自动添加token到请求头
axios.interceptors.request.use(
  config => {
    const token = getSessionStorage('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器，处理token相关错误
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      // 处理401未授权错误（token无效或过期）
      if (error.response.status === 401) {
        // 清除用户信息和token
        removeSessionStorage('user');
        removeSessionStorage('token');
        
        // 跳转到登录页面
        router.push('/login');
        alert('登录已过期，请重新登录');
      }
    }
    return Promise.reject(error);
  }
);

const app = createApp(App);

// 将工具函数和库挂载到全局属性
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$qs = qs;
app.config.globalProperties.$getCurDate = getCurDate;
app.config.globalProperties.$setSessionStorage = setSessionStorage;
app.config.globalProperties.$getSessionStorage = getSessionStorage;
app.config.globalProperties.$removeSessionStorage = removeSessionStorage;
app.config.globalProperties.$setLocalStorage = setLocalStorage;
app.config.globalProperties.$getLocalStorage = getLocalStorage;
app.config.globalProperties.$removeLocalStorage = removeLocalStorage;

// 路由守卫
router.beforeEach((to, from, next) => {
  let user = sessionStorage.getItem('user');
  // 除了登录、注册、首页、商家列表、商家信息之外，都需要判断是否登录
  if (!(to.path === '/' || to.path === '/index' || to.path === '/businessList' || to.path === '/businessInfo' || to.path === '/login' || to.path === '/register')) {
    if (user == null) {
      router.push('/login');
      location.reload();
    }
  }
  next();
});

// 使用路由
app.use(router);

// 禁用生产提示
app.config.productionTip = false;

// 挂载应用
app.mount('#app');